<script setup>
import { ref, reactive, toRaw, computed } from "vue";
import { useRouter } from "vue-router";
import { PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { useI18n } from "vue-i18n";
// import { reg_developer, reg_company_developer } from "@/api/request";
import { reg_developer, reg_company_developer, sendCode } from "@/utils/api";
const { t } = useI18n();
const router = useRouter();
const hasType = computed(() => router.currentRoute.value.query.type);
console.log("hasType: =》", hasType);
const formRef = ref();
const iconLoading = ref(false);
const labelCol = {
  style: {
    span: 24,
  },
};
const wrapperCol = {
  span: 24,
};
const formState = reactive({
  info: "",
  enterpriseName: "",
  mechanismType: "",
  UCuCode: "",
  address: "",
  businessLicense: [],
  corporateName: "",
  corporateNumber: "",
  idCardFront: [],
  idCardBack: [],
  authentication: [],
  //联系人
  contactName: "",
  telephone: "",
  getCode: "",
  email: "",
  socialType: "1",
  socialStyle: "",
  contact_address: "",
  agree: false,
  // 个人
  developerName: "",
  documentNumber: "",
});

// 勾选校验
const checkAgreement = (rule, value) => {
  if (!value) {
    return Promise.reject(
      new Error("请我已阅读并同意《百分网游戏盒子开发者协议条款》和《隐私政策》")
    );
  }
  return Promise.resolve();
};
// 验证码
const phoneRegex = /^1[3-9]\d{9}$/;
const gerCaptcha = () => {
  if (!formState.telephone) {
    message.error(t("message.pleaseEnterPhone"));
    return;
  }
  if (!phoneRegex.test(formState.telephone)) {
    message.error(t("message.invalidPhoneNumber"));
    return;
  }
  sendCode({
    phone: formState.telephone,
  }).then((res) => {
    if (res.code === 200) {
      message.success(t("message.msg"));
    } else {
      message.error(res.msg);
    }
  });
  startCountdown();
};
const countdownConfig = reactive({
  seconds: 60,
  getCodeLoading: false,
  timerId: null,
});
const startCountdown = () => {
  if (!countdownConfig.getCodeLoading && formState.telephone) {
    countdownConfig.getCodeLoading = true;
    countdownConfig.timerId = setInterval(() => {
      if (countdownConfig.seconds > 0) {
        countdownConfig.seconds--;
      } else {
        clearInterval(countdownConfig.timerId);
        countdownConfig.getCodeLoading = false;
        countdownConfig.seconds = 60; // 重置秒数
      }
    }, 1000);
  }
};

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
const previewVisible = ref(false);
const previewImage = ref("");
const previewTitle = ref("");
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = "";
};
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};

const previewVisible2 = ref(false);
const previewImage2 = ref("");
const previewTitle2 = ref("");
const handleCancel2 = () => {
  previewVisible2.value = false;
  previewTitle2.value = "";
};
const handlePreview2 = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage2.value = file.url || file.preview;
  previewVisible2.value = true;
  previewTitle2.value = file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};

const onSave = (values) => {
  console.log("values: ", 111);
  // iconLoading.value = true;
  formRef.value
    .validate()
    .then(async () => {
      console.log("Success:", values);
      console.log("values", formState, toRaw(formState));
      const formData = new FormData();
      // 厂商
      formData.append("name", formState.info);
      // 联系人
      formData.append("contact_name", formState.contactName);
      formData.append("contact_phone", formState.telephone);
      formData.append("contact_email", formState.email);
      // formData.append('company_address', formState.mechanismType)
      formData.append("contact_qq_wx", formState.socialStyle);
      formData.append("contact_qq_wx_type", formState.socialType);
      formData.append("contact_address", formState.contact_address);
      if (hasType.value == "personage") {
        formData.append("legal_name", formState.developerName);
        formData.append("legal_card", formState.documentNumber);
        // 图片
        formData.append("legal_is_img", formState.idCardFront[0].originFileObj || []);
        formData.append("legal_the_img", formState.idCardBack[0].originFileObj || []);

        console.log("formData: ", formData);
        reg_developer(formData)
          .then((res) => {
            console.log("res: ", res);
            iconLoading.value = false;
            if (res.code === 1) {
              // console.log(res, "res--1");
              router.push("/");
            } else {
              message.error(res.msg);
            }
          })
          .catch(() => {
            iconLoading.value = false;
          });
      } else {
        console.log(1111, "1----企业开发者");
        formData.append("company_name", formState.enterpriseName);
        formData.append("company_type", formState.mechanismType);
        formData.append("company_code", formState.UCuCode);
        formData.append("company_address", formState.address);
        formData.append("license_img", formState.businessLicense[0].originFileObj);
        formData.append("legal_name", formState.corporateName);
        formData.append("legal_card", formState.corporateNumber);
        // 法人代表身份证
        formData.append("legal_is_img", formState.idCardFront[0].originFileObj);
        formData.append("legal_the_img", formState.idCardBack[0].originFileObj);
        formData.append("official", formState.authentication[0].originFileObj);

        reg_company_developer(formData)
          .then((res) => {
            console.log("res: -企业开发者", res);
            iconLoading.value = false;
            if (res.code === 1) {
              console.log(res, "res---企业开发者");
              // router.push("/");
            }
            else {
              message.error(res.msg);
            }
          })
          .catch(() => {
            iconLoading.value = false;
          });
      }

      // 注册完后进入页面
      // await router.push("/");
    })
    .catch((e) => {
      console.log("e: ", e);
    });
};
const resetForm = () => {
  formRef.value.resetFields();
  formState.idCardBack = [];
  iconLoading.value = false;
};
const merchantLabel = computed(() => {
  if (hasType.value == "firm") {
    return "厂商名称（在游戏详情页，向玩家展示的名称，创建后则无法修改）";
  } else {
    return "厂商信息（在游戏详情页，向玩家展示的名称，创建后则无法修改）";
  }
});
const idCardLabel = computed(() => {
  if (hasType.value == "firm") {
    return "法人代表身份证扫描件（格式必须为JPG或PNG）";
  } else {
    return "身份证扫描件（格式必须为JPG或PNG）";
  }
});
</script>
<template>
  <div>
    <h3 style="display: block; font-size: 18px; margin-bottom: 20px">注册信息</h3>
    <a-form
      layout="vertical"
      :model="formState"
      ref="formRef"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item
        :label="merchantLabel"
        name="info"
        :rules="[{ required: true, message: '请输入厂商名称', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.info"
          class="my_input"
          placeholder="请输入名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="开发者姓名"
        name="developerName"
        v-if="hasType == 'personage'"
        :rules="[{ required: true, message: '请输入开发者姓名', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.developerName"
          class="my_input"
          placeholder="请输入开发者姓名"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="身份证号码"
        name="documentNumber"
        v-if="hasType == 'personage'"
        :rules="[{ required: true, message: '请输入证件号码', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.documentNumber"
          class="my_input"
          placeholder="请输入证件号码"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="企业名称（该名称与营业执照上名称统一）"
        name="enterpriseName"
        v-if="hasType == 'firm'"
        :rules="[{ required: true, message: '请输入企业名称', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.enterpriseName"
          class="my_input"
          placeholder="请输入企业名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="机构类型"
        v-if="hasType == 'firm'"
        name="mechanismType"
        :rules="[{ required: true, message: '请输入机构类型', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.mechanismType"
          class="my_input"
          placeholder="请输入机构类型"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="统一信用社代码"
        name="UCuCode"
        v-if="hasType == 'firm'"
        :rules="[{ required: true, message: '请输入证件号码', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.UCuCode"
          class="my_input"
          placeholder="请输入证件号码"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="注册地址"
        name="address"
        v-if="hasType == 'firm'"
        :rules="[{ required: true, message: '请输入注册地址', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.address"
          class="my_input"
          placeholder="请输入注册地址"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="营业执照扫描件（格式必须为JPG或PNG）"
        name="businessLicense"
        v-if="hasType == 'firm'"
      >
        <div class="upload-container">
          <a-upload
            v-model:fileList="formState.businessLicense"
            list-type="picture-card"
            :max-count="1"
          >
            <div v-if="formState.businessLicense.length < 1">
              <PlusOutlined
                :style="{
                  fontSize: '32px',
                  color: 'rgba(222, 222, 222, 1)',
                }"
              />
              <div class="colorGreen">点击或拖拽上传</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>
      <a-row :gutter="[8, 8]" class="my_input" v-if="hasType == 'firm'">
        <a-col :span="12">
          <a-form-item
            label="法人代表姓名"
            name="corporateName"
            :rules="[
              {
                required: true,
                message: '请输入法人代表姓名',
                trigger: 'change',
              },
            ]"
          >
            <a-input
              v-model:value="formState.corporateName"
              placeholder="请输入法人代表姓名"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="法人代表身份证号码"
            name="corporateNumber"
            :rules="[
              {
                required: true,
                message: '请输入法人代表身份证号码',
                trigger: 'change',
              },
              {
                pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[0-9Xx]$/,
                message: '请输入有效的身份证号码',
                trigger: 'blur',
              }
            ]"
          >
            <a-input
              v-model:value="formState.corporateNumber"
              placeholder="请输入法人代表身份证号码"
              allow-clear
              show-count :maxlength="18"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item
        :label="idCardLabel"
        name="idCardFront"
        :rules="[{ required: true, message: '请上传身份证', trigger: 'change' }]"
      >
        <a-row :gutter="[8, 8]" class="my_input">
          <a-col :span="8">
            <div class="upload-container">
              <a-upload
                v-model:fileList="formState.idCardFront"
                list-type="picture-card"
                :max-count="1"
                @preview="handlePreview"
                style="width: 100%"
              >
                <div v-if="formState.idCardFront.length < 1" class="pload-container">
                  <PlusOutlined
                    :style="{
                      fontSize: '32px',
                      color: 'rgba(222, 222, 222, 1)',
                    }"
                  />
                  <div class="colorGreen">身份证正面</div>
                </div>
              </a-upload>
              <a-modal
                :open="previewVisible"
                :title="previewTitle"
                :footer="null"
                action=""
                @preview="handlePreview"
                @cancel="handleCancel"
              >
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="upload-container">
              <a-upload
                v-model:fileList="formState.idCardBack"
                list-type="picture-card"
                :max-count="1"
                @preview="handlePreview2"
                style="width: 210px; height: 120px"
              >
                <div v-if="formState.idCardBack.length < 1">
                  <PlusOutlined
                    :style="{
                      fontSize: '32px',
                      color: 'rgba(222, 222, 222, 1)',
                    }"
                  />
                  <div class="colorGreen">身份证反面</div>
                </div>
              </a-upload>
              <a-modal
                :open="previewVisible2"
                :title="previewTitle2"
                :footer="null"
                @cancel="handleCancel2"
              >
                <img alt="example" style="width: 100%" :src="previewImage2" />
              </a-modal>
            </div>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item
        label="认证公函（格式必须为JPG或PNG）"
        name="authentication"
        v-if="hasType == 'firm'"
      >
        <div class="upload-container">
          <a-upload
            v-model:fileList="formState.authentication"
            list-type="picture-card"
            :max-count="1"
          >
            <div v-if="formState.authentication.length < 1">
              <PlusOutlined
                :style="{
                  fontSize: '32px',
                  color: 'rgba(222, 222, 222, 1)',
                }"
              />
              <div class="colorGreen">点击或拖拽上传</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>
      <div class="form_tips my_input" v-if="hasType == 'firm'">
        <i class="tips">
          <img src="../../assets/icon/icon.png" alt="" class="imgs" />温馨提示</i
        ><br />
        <i
          >① 下载<a style="color: rgba(76, 200, 126, 1)" href="javascript:;"
            >《光放认证通用申请公函》</a
          >，填写完整后加盖红色公章，上传清晰的扫描件。有效期为一年，需要每年更新认证公函。如有问题，可联系在线客服。</i
        ><br />
      </div>
      <h3 style="display: block; font-size: 18px; margin-bottom: 20px">
        联系人信息<span style="font-size: 12px; color: #6e6e6e"
          >（为了紧急情况下可以联系到开发者，请在此处填商务人员的联系方式）</span
        >
      </h3>

      <a-form-item
        label="联系人姓名（需要验证，用来接受平台通知）"
        name="contactName"
        :rules="[{ required: true, message: '请输入联系人姓名', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.contactName"
          class="my_input"
          placeholder="请输入姓名"
          allow-clear
        />
      </a-form-item>
      <a-row :gutter="[8, 8]" class="my_input">
        <a-col :span="12">
          <a-form-item
            label="联系手机号（需要验证，用来接受平台通知）"
            name="telephone"
            :rules="[
              {
                required: true,
                message: '请输入联系手机号',
                trigger: 'change',
              },
            ]"
          >
            <a-input
              v-model:value="formState.telephone"
              placeholder="请输入手机号"
              allow-clear
              class="w100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item-rest>
            <a-button
              class="m12px mt30px"
              htmlType="submit"
              :disabled="countdownConfig.seconds != 60"
              @click="gerCaptcha"
              >{{
                countdownConfig.seconds != 60
                  ? `${countdownConfig.seconds}秒`
                  : "获取验证码"
              }}</a-button
            >
          </a-form-item-rest>
        </a-col>
        <a-col :span="8">
          <!-- <a-form-item name="getCode">
            <a-input
              v-model:value="formState.getCode"
              placeholder="请输入验证码"
              class="mt30px w102%"
              :rules="[
                {
                  required: true,
                  message: '请输入验证码',
                  trigger: 'change',
                },
              ]"
            />
          </a-form-item> -->
          <a-form-item
            name="getCode"
            class="mt30px w102%"
            :rules="[
              {
                required: true,
                message: '请输入验证码',
                trigger: 'change',
              },
            ]"
          >
            <a-input
              v-model:value="formState.getCode"
              placeholder="请输入验证码"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item
        label="联系邮箱（用来接受平台通知）"
        name="email"
        :rules="[{ required: true, message: '请输入邮箱', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.email"
          class="my_input"
          placeholder="请输入邮箱"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="联系QQ/微信（常用的QQ/微信至少填写一项）"
        name="socialStyle"
        :rules="[{ required: true, message: '请输入社交方式', trigger: 'change' }]"
      >
        <a-input-group compact>
          <a-select v-model:value="formState.socialType">
            <a-select-option value="1">QQ</a-select-option>
            <a-select-option value="2">微信</a-select-option>
          </a-select>
          <a-input v-model:value="formState.socialStyle" style="width: 25%" />
        </a-input-group>
      </a-form-item>
      <a-form-item
        label="联系地址（用于邮寄合同地址使用）"
        name="contact_address"
        :rules="[{ required: true, message: '请输入地址', trigger: 'change' }]"
      >
        <a-input
          v-model:value="formState.contact_address"
          class="my_input"
          placeholder="请输入地址"
          allow-clear
        />
      </a-form-item>
      <h3 style="display: block; font-size: 18px; margin-bottom: 20px">合作协议</h3>
      <a-form-item
        name="agree"
        :rules="[{ validator: checkAgreement, trigger: 'change' }]"
      >
        <a-checkbox v-model:checked="formState.agree">
          <span style="font-size: 16px">
            我已阅读并同意百分网<a
              href="/developer-agreement"
              style="color: rgba(76, 200, 126, 1)"
              >《开发者协议条款》</a
            >和<a href="/privacy-policy" style="color: rgba(76, 200, 126, 1)"
              >《隐私政策》</a
            >
          </span>
        </a-checkbox>
      </a-form-item>
      <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button
          htmlType="submit"
          style="margin-right: 16px; background-color: rgba(76, 200, 126, 1)"
          type="primary"
          @click="onSave"
          :loading="iconLoading"
          >确认提交</a-button
        >
        <a-button style="margin-left: 8px" @click="resetForm">取消</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style lang="less" scoped>
.my_input {
  width: 60%;
}

.upload-container {
  width: 210px;
  height: 120px;
}

:deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper .ant-upload.ant-upload-select) {
  width: 100%;
}

:deep(.ant-upload-list-item-container) {
  width: 210px;
  height: 120px;
}

.form_tips {
  font-size: 14px;
  background: #edfaf1;
  border-radius: 4px 4px 4px 4px;
  margin-bottom: 16px;
  padding: 12px;
  color: #6e6e6e;

  i {
    font-style: normal;
  }
}

.colorGreen {
  color: #969696;
}

.tips {
  display: inline-flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 18px;
  color: #3c3c3c;
  font-weight: 400;
  img{
    width: 18px;
  }
}

:deep(:where(.css-dev-only-do-not-override-12oi33h).ant-upload-wrapper.ant-upload-picture-card-wrapper
    .ant-upload-list.ant-upload-list-picture-card
    .ant-upload-list-item-container) {
  width: 100%;
}
</style>
